﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Runtime.Caching;
using blackhouse.Data;
using blackhouse.WebNemo.Business;
using blackhouse.WebNemo.Data.Cache;

namespace blackhouse.StareKino.Web.Discounts {
    public class LengthOfStayDiscount : Aparts.Web.Discounts.LengthOfStayDiscount {

        #region Fields

        private const string Ckey = "lengthofstaydiscount";

        #endregion

        protected override LengthOfStayData[] GetDbData() {
            LengthOfStayData[] data = null;
            if (MemoryCache.Default.Contains(Ckey))
                data = (LengthOfStayData[])MemoryCache.Default[Ckey];
            if (data == null) {
                var ldata = new List<LengthOfStayData>();
                var reader = this.GetDataReader();
                while (reader.Read()) {
                    var di = this.ReadItem(reader);
                    ldata.Add(di);
                }
                reader.Close();
                data = ldata.ToArray();
                this.SetCache(data);
            }
            return data;
        }

        private void SetCache(object cacheObj) {
            var cip = new CacheItemPolicy();
            cip.SlidingExpiration = TimeSpan.FromMinutes(20);
            cip.ChangeMonitors.Add(new NemoChangeMonitor(new CacheGroupIdsProvider("APARTAMENTY", "Z_CENA__DLUGOSC_POBYTU")));
            var ci = new CacheItem(Ckey, cacheObj);
            MemoryCache.Default.Add(ci, cip);
        }

        private IDataReader GetDataReader() {
            var dataHelper = new MsSqlAdoDataHelper(ConfigurationManager.AppSettings["MSSQLConnectionString"]);
            dataHelper.ProcedureName = "bhp_DiscountsLengthOfStayGet";
            return dataHelper.Execute();
        }

        private LengthOfStayData ReadItem(IDataReader reader) {
            return new LengthOfStayData
            {
                ApartmentTypeId = Convert.ToInt32(reader["ApartmentTypeId"]),
                LenghtOfStay = Convert.ToInt32(reader["DayCount"]),
                Rabat = Convert.ToSingle(reader["Rabat"])
            };
        }

    }
}